﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.DiaoDongService;
using CommunitySystem.EmpbasicService;

namespace CommunitySystem
{
    public partial class DiaoDongWindow_DanWeiNeiZhuanRen : ChildWindow
    {
        private DiaoDongService.DiaoDongModel model = new DiaoDongService.DiaoDongModel();
        private DiaoDongService.DiaoDongServiceClient Client = new DiaoDongService.DiaoDongServiceClient();
        private EmpbasicService.EmpBasicServiceClient empclient = new EmpbasicService.EmpBasicServiceClient();
        private ObservableCollection<EmpbasicService.DiaoDongModel> modellist = new ObservableCollection<EmpbasicService.DiaoDongModel>();
        public int ID;
        public int OrgID;
        public bool IsNew = false;
        public string SFCK = "";
        public string OrgName = "";
        public ObservableCollection<BianZhiModel> BianZhiModels = new ObservableCollection<BianZhiModel>();
        public ObservableCollection<BianZhiModel> SelectedModels = new ObservableCollection<BianZhiModel>();
        public DiaoDongWindow_DanWeiNeiZhuanRen(int orgid, int iD, bool isnew, string shifouchakan,string orgname)
        {
            InitializeComponent();
            ID = iD;
            OrgID = orgid;
            IsNew = isnew;
            SFCK = shifouchakan;
            OrgName = orgname;
            stat.Visibility = System.Windows.Visibility.Collapsed;
            empclient.GetBianZhiModelCompleted += new EventHandler<EmpbasicService.GetBianZhiModelCompletedEventArgs>(Client_GetBianZhiModelCompleted);
            Client.AddDiaoDongCompleted += new EventHandler<AddDiaoDongCompletedEventArgs>(Client_AddDiaoDongCompleted);
            Client.UpdateDiaoDongCompleted += new EventHandler<UpdateDiaoDongCompletedEventArgs>(Client_UpdateDiaoDongCompleted);
            empclient.GetEmp_BasicInfoCompleted += new EventHandler<EmpbasicService.GetEmp_BasicInfoCompletedEventArgs>(empclient_GetEmp_BasicInfoCompleted);
            if (shifouchakan == "查看")
            {
                huiyiriqi.IsEnabled =
                    biaoti.IsEnabled =
                    keshi.IsEnabled = zw.IsEnabled = begin.IsEnabled = end.IsEnabled = false;
            }
            else
            {
                huiyiriqi.IsEnabled =
                    biaoti.IsEnabled =
                    keshi.IsEnabled = zw.IsEnabled = begin.IsEnabled = end.IsEnabled = true;
            }
            //tt.OnSelectionChanged += new OnSelectionChangedEvent(tt_OnSelectionChanged);
            empclient.GetEmp_BasicInfoModelByCardNoCompleted += 
                new EventHandler<EmpbasicService.GetEmp_BasicInfoModelByCardNoCompletedEventArgs>(empclient_GetEmp_BasicInfoModelByCardNoCompleted);
            empclient.GetEmp_BasicInfoModelByCardNoAsync("", OrgID);
            Client.GetDiaoDongCompleted += new EventHandler<GetDiaoDongCompletedEventArgs>(Client_GetDiaoDongCompleted);
            empclient.GetBianZhiDetailModelCompleted += new EventHandler<GetBianZhiDetailModelCompletedEventArgs>(Client2_GetBianZhiDetailModelCompleted);
            empclient.GetBianZhiDetailModelAsync(OrgID.ToString(), "");
        }
        void Client2_GetBianZhiDetailModelCompleted(object sender, GetBianZhiDetailModelCompletedEventArgs e)
        {
            SelectedModels.Clear();
            BianZhiModels = e.Result;
            if (BianZhiModels != null && BianZhiModels.Count > 0)
            {
                string zhurenkeyong = "";
                int i1 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao)
                            ? BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao
                            : "0");
                int i2 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(
                            BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou)
                            ? BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou
                            : "0");

                int i3 = 0;
                foreach (BianZhiModel b in BianZhiModels)
                {
                    if (!string.IsNullOrEmpty(b.ZhuRenJieYongQingKuang) && b.ZhuRenJieYongQingKuang != "无")
                    {
                        if (Math.Abs(Convert.ToInt32(b.ZhuRenJieYongQingKuang)) > i3)
                            i3 = Convert.ToInt32(b.ZhuRenJieYongQingKuang);
                    }
                }
                int i4 =
                    Convert.ToInt32(
                        BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                            ZhuRenChaoZhiQingKuang == "无"
                            ? "0"
                            : BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                                  ZhuRenChaoZhiQingKuang);
                zhurenkeyong = (i1 - i2 + i3 + i4).ToString();

                string fuzhurenkeyong = "";
                int f1 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao)
                            ? BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao
                            : "0");
                int f2 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(
                            BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou)
                            ? BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou
                            : "0");

                int f3 = 0;
                foreach (BianZhiModel b in BianZhiModels)
                {
                    if (!string.IsNullOrEmpty(b.FuZhuRenJieYongQingKuang) && b.FuZhuRenJieYongQingKuang != "无")
                    {
                        if (Math.Abs(Convert.ToInt32(b.FuZhuRenJieYongQingKuang)) > f3)
                            f3 = Convert.ToInt32(b.FuZhuRenJieYongQingKuang);
                    }
                }
                int f4 =
                    Convert.ToInt32(
                        BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                            FuZhuRenChaoZhiQingKuang == "无"
                            ? "0"
                            : BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                                  FuZhuRenChaoZhiQingKuang);
                fuzhurenkeyong = (f1 - f2 + f3 + f4).ToString();
                foreach (BianZhiModel i in BianZhiModels)
                {
                    i.ZhuRenShiJi = zhurenkeyong;
                    i.FuZhuRenShiJi = fuzhurenkeyong;
                }
                if (BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Count() > 0)
                {
                    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true))
                    {
                        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeLingDao) ? Convert.ToInt32(i.ZhengKeLingDao) : 0;
                        int renshu = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p => !string.IsNullOrEmpty(p.zhengkeshiyou) ? Convert.ToInt32(p.zhengkeshiyou) : 0);
                        int jieyong = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p =>
                            p.ZhengKeJieYongQingKuang != "无" ? Convert.ToInt32(p.ZhengKeJieYongQingKuang) : 0);
                        int chaozhi = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p =>
                            p.ZhengKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.ZhengKeChaoZhiQingKuang) : 0);

                        i.ZhengKeShiJi =
                            (zhiwhu - renshu + jieyong + chaozhi)
                                .ToString();
                        //i.ZhengKeShiJi =
                        //    (Convert.ToInt32(
                        //        BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).OrderBy(p => p.ZhengKeShiJi).
                        //            FirstOrDefault().ZhengKeShiJi) +
                        //     BianZhiModels.Sum(
                        //         p => p.ZhengKeJieYongQingKuang != "无" ? Convert.ToInt32(p.ZhengKeJieYongQingKuang) : 0) +
                        //     BianZhiModels.Sum(
                        //         p => p.ZhengKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.ZhengKeChaoZhiQingKuang) : 0))
                        //        .ToString();
                    }
                }

                if (BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Count() > 0)
                {
                    //foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true))
                    //{
                    //    i.FuKeShiJi =
                    //        BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).OrderBy(p => p.FuKeShiJi).
                    //            FirstOrDefault().FuKeShiJi;
                    //}
                    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true))
                    {
                        i.FuKeShiJi =
                            (Convert.ToInt32(
                                BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).OrderBy(p => p.FuKeShiJi).
                                    FirstOrDefault().FuKeShiJi) +
                             BianZhiModels.Sum(
                                 p => p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0) +
                             BianZhiModels.Sum(
                                 p => p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0))
                                .ToString();

                        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeFeiLingDao) ? Convert.ToInt32(i.ZhengKeFeiLingDao) : 0;
                        int renshu = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p => !string.IsNullOrEmpty(p.fukeshiyou) ? Convert.ToInt32(p.fukeshiyou) : 0);
                        int jieyong = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p =>
                            p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0);
                        int chaozhi = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p =>
                            p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0);

                        i.FuKeShiJi =
                            (zhiwhu - renshu + jieyong + chaozhi)
                                .ToString();
                    }
                }
            }
        }
        void Client_GetBianZhiModelCompleted(object sender, EmpbasicService.GetBianZhiModelCompletedEventArgs e)
        {
            keshi.ItemsSource = null;
            keshi.ItemsSource = e.Result;
            if (keshi.ItemsSource != null)
            {
                for (int i = 0; i < ((ObservableCollection<BianZhiModel>)keshi.ItemsSource).Count; i++)
                {
                    if (((ObservableCollection<BianZhiModel>)keshi.ItemsSource)[i].JiGouMingCheng == model.NewPositionName)
                        keshi.SelectedIndex = i;
                }
            }
        }
        void gangwei_SelectionChanged1(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                model.NewPositionName = ((BianZhiModel)((((ComboBox)sender).SelectedItem))).JiGouMingCheng;
            }

        }
        void empclient_GetEmp_BasicInfoModelByCardNoCompleted(object sender, EmpbasicService.GetEmp_BasicInfoModelByCardNoCompletedEventArgs e)
        {
            biaoti.ItemsSource = null;
            modellist.Clear();
            foreach (EmpbasicService.DiaoDongModel i in e.Result)
            {
                modellist.Add(i);
            }
            biaoti.ItemsSource = e.Result;
            if(IsNew)
            {
                model.Type = "单位内转任";
                empclient.GetBianZhiModelAsync(OrgID.ToString(), 0);
                this.DataContext = model;
            }
            else
            {
                Client.GetDiaoDongAsync("", ID, "", "", "");
            }
        }

        void Client_GetDiaoDongCompleted(object sender, GetDiaoDongCompletedEventArgs e)
        {
            if (e.Result != null)
                model = e.Result[0];
            empclient.GetBianZhiModelAsync(OrgID.ToString(), 0);
            this.DataContext = model;
            if (modellist.Count > 0)
            {
                for (int i = 0; i < modellist.Count; i++)
                {
                    if (modellist[i].EmpbasicID == model.EmpbasicID)
                        biaoti.SelectedIndex = i;
                }
            }
            
        }

        void tt_OnSelectionChanged(object sender, object NewValue, object OldValue)
        {
            if (NewValue != null)
            {
                if (NewValue.ToString() == "领导职务" )
                {
                    stat.Visibility = System.Windows.Visibility.Visible;
                    stat1.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    stat.Visibility = System.Windows.Visibility.Collapsed;
                    stat1.Visibility = System.Windows.Visibility.Visible;
                    
                }
            }

        }
        void gangwei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                model.EmpbasicID = ((EmpbasicService.DiaoDongModel)((((ComboBox)sender).SelectedItem))).EmpbasicID;
                model.DutyAttribute =
                    ((EmpbasicService.DiaoDongModel) ((((ComboBox) sender).SelectedItem))).DutyAttribute;
                model.DutyLevel = ((EmpbasicService.DiaoDongModel) ((((ComboBox) sender).SelectedItem))).DutyLevel;
                if (model.DutyAttribute.ToString() == "领导职务")
                {
                    stat.Visibility = System.Windows.Visibility.Visible;
                    stat1.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    stat.Visibility = System.Windows.Visibility.Collapsed;
                    stat1.Visibility = System.Windows.Visibility.Visible;

                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (Valid())
            {
                model.Status = "未审核";
                if (IsNew)
                {
                    model.RZQMSJ = DateTime.Today;
                    model.NewOrgID = OrgID;
                    empclient.GetEmp_BasicInfoAsync("0", "(" + model.EmpbasicID.ToString() + ")", "", "", 0, 20, "在职", "", true,false);
                    
                }
                else Client.UpdateDiaoDongAsync(model);
            }
        }
        void empclient_GetEmp_BasicInfoCompleted(object sender, EmpbasicService.GetEmp_BasicInfoCompletedEventArgs e)
        {
            if(e.Result != null && e.Result.Count > 0)
            {
                Emp_BasicInfoModel x = e.Result[0];
                model.Name = x.Name;
                model.CardNo = x.CardNo;
                model.Gender = x.Gender;
                model.OrgName = x.OrgName;
                model.PositionName = x.PositionName;
                model.DutyName = x.DutyNo;
                model.DutyLevel = x.DutyLevel;
                model.OrgID = Convert.ToInt32(x.OrgID);
                model.NewOrgName = OrgName;
                model.DutyAttribute = x.DutyAttribute;
                model.ZWCCSJ = x.JobDate;
                if (!string.IsNullOrEmpty(x.RXRZWSXSJ))
                    model.ZWSXSJ = Convert.ToDateTime(x.RXRZWSXSJ);
                Client.AddDiaoDongAsync(model);
            }
        }
        void Client_UpdateDiaoDongCompleted(object sender, UpdateDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("编辑成功！");
                this.DialogResult = true;
            }
        }

        void Client_AddDiaoDongCompleted(object sender, AddDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("新增成功！");

                this.DialogResult = true;
            }
        }

        public bool Valid()
        {
            if (model.EmpbasicID == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择人员！");
                return false;
            }
            if (string.IsNullOrEmpty(model.HuiYiDate.ToString()) || Convert.ToDateTime(model.HuiYiDate) == Convert.ToDateTime("1900-01-01"))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入会议日期！");
                return false;
            }
            if (string.IsNullOrEmpty(model.NewPositionName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员现科室！");
                return false;
            }
            if (string.IsNullOrEmpty(model.NewDutyName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员现职位！");
                return false;
            }
            if (string.IsNullOrEmpty(model.DutyAttribute))
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请输入人员职务属性！");
                return false;
            }
            if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "领导职务")
            {
                foreach (BianZhiModel i in BianZhiModels)
                {
                    if (i.OrgID == OrgID && i.JiGouMingCheng == model.NewPositionName && Convert.ToInt32(!string.IsNullOrEmpty(i.ZhengKeShiJi) ? i.ZhengKeShiJi : "0") <= 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("所选科室没有对应的职数可用！");
                        return false;
                    }
                }
                //if (BianZhiModels.Where(p => p.OrgID == OrgID && p.JiGouMingCheng == model.NewPositionName && Convert.ToInt32(!string.IsNullOrEmpty(p.ZhengKeShiJi) ? p.ZhengKeShiJi : "0") > 0).FirstOrDefault() == null)
                //{
                //    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                //    return false;
                //}
            }
            if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "领导职务")
            {
                if (BianZhiModels.Where(p => p.OrgID == OrgID && p.JiGouMingCheng == model.NewPositionName && Convert.ToInt32(!string.IsNullOrEmpty(p.FuKeShiJi) ? p.FuKeShiJi : "0") > 0).FirstOrDefault() == null)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                    return false;
                }
            }
            if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "非领导职务")
            {
                if (BianZhiModels.Where(p => p.OrgID == OrgID && p.JiGouMingCheng == model.NewPositionName && Convert.ToInt32(!string.IsNullOrEmpty(p.ZhuRenShiJi) ? p.ZhuRenShiJi : "0") > 0).FirstOrDefault() == null)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                    return false;
                }
            }
            if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "非领导职务")
            {
                if (BianZhiModels.Where(p => p.OrgID == OrgID && p.JiGouMingCheng == model.NewPositionName && Convert.ToInt32(!string.IsNullOrEmpty(p.FuZhuRenShiJi) ? p.FuZhuRenShiJi : "0") > 0).FirstOrDefault() == null)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                    return false;
                }
            }
            if (model.DutyAttribute == "领导职务")
            {
                if (string.IsNullOrEmpty(model.Begindate.ToString()) || Convert.ToDateTime(model.Begindate) == Convert.ToDateTime("1900-01-01"))
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入任职开始日期！");
                    return false;
                }
                if (string.IsNullOrEmpty(model.Enddate.ToString()) || Convert.ToDateTime(model.Enddate) == Convert.ToDateTime("1900-01-01"))
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入任职结束日期！");
                    return false;
                }
            }
            return true;
        }
    }
}
